﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Warehouse.Web.AppCode;

namespace Warehouse.Web.Purchase
{
    public partial class BillHistory : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.ddlSupplier.DataSource = DataAccess.Supplier.GetSuppliers();
                this.ddlSupplier.DataBind();

                if (Request.QueryString.AllKeys.Contains("search"))
                {
                    DateTime dtStart = DateTime.Parse(Request.QueryString["Start"]);
                    DateTime dtEnd = DateTime.Parse(Request.QueryString["End"]);
                    this.tbStartDate.Text = dtStart.ToString("yyyy-MM-dd");
                    this.tbEndDate.Text = dtEnd.ToString("yyyy-MM-dd");

                    int supplierId = int.Parse(Request.QueryString["SupplierID"]);

                    for (int index = 0; index < this.ddlSupplier.Items.Count; index++)
                    {
                        if (this.ddlSupplier.Items[index].Value == supplierId.ToString())
                        {
                            this.ddlSupplier.SelectedIndex = index;
                            break;
                        }
                    }

                    LoadData(supplierId, dtStart, dtEnd.AddDays(1));
                }
                else
                {
                    this.tbStartDate.Text = DateTime.Now.AddDays(1 - DateTime.Now.Day).ToString("yyyy-MM-dd"); ;
                    this.tbEndDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                }
            }
        }

        void LoadData(int supplierId, DateTime startDate, DateTime endDate)
        {
            var purchaseviews = DataAccess.CustomeEntity<DataAccess.PurchaseView>.GetList(p => p.SupplierID == supplierId && p.PurchaseDate >= startDate && p.PurchaseDate < endDate && p.Status == (int)DataAccess.BillStatus.Default).ToList();
            var paymentviews = DataAccess.CustomeEntity<DataAccess.PaymentView>.GetList(p => p.SupplierID == supplierId && p.ReceiptDate >= startDate && p.ReceiptDate < endDate && p.Status == (int)DataAccess.BillStatus.Default).ToList();

            List<DataWrapper> datasource = new List<DataWrapper>();
            datasource.AddRange(purchaseviews.Select(p =>
             {
                 string op = string.Empty;
                 switch ((DataAccess.PurchaseBillType)p.Type)
                 {
                     case DataAccess.PurchaseBillType.Purchase:
                         op = "进货";
                         break;
                     case Warehouse.DataAccess.PurchaseBillType.Gift:
                         op = "赠品";
                         break;
                     case Warehouse.DataAccess.PurchaseBillType.Return:
                         op = "退货";
                         break;
                 }
                 return new DataWrapper()
             {
                 Group = p.BillID.ToString(),
                 Date = p.PurchaseDate,
                 Summary = string.Format("{0}: {1} {2} {3} ({4})  {5}*{6}", op, p.Name, p.Grade, p.Model, p.Specification, p.Price, p.Count),
                 ShouldPay = (p.Type == (int)DataAccess.PurchaseBillType.Return ? -1 : 1) * p.Amount,
                 RealPay = 0,
                 Type = p.Type,
                 BillID = p.BillID,
                 CreateDate = p.CreateDate
             };
             }));
            datasource.AddRange(paymentviews.Select(p =>
            {
                var d = new DataWrapper()
                 {
                     Group = ("P_" + p.BillID.ToString()),
                     Date = p.ReceiptDate,
                     Summary = string.Format("【{0}】 {1} {2:C2}", p.AccountName, p.IsIncome ? "收款" : "付款", p.Amount),
                     ShouldPay = 0,
                     RealPay = (p.IsIncome ? -1 : 1) * p.Amount,
                     BillID = p.BillID,
                     Type = p.IsIncome ? -2 : -1,
                     CreateDate = p.CreateDate
                 };
                if (p.PruchageBillID.HasValue)
                {
                    var purcharsebill = purchaseviews.FirstOrDefault(arg => arg.BillID == p.PruchageBillID.Value);
                    d.Group = p.PruchageBillID.Value.ToString();
                    d.BillID = p.PruchageBillID.Value;
                    d.Type = purcharsebill.Type;
                    d.CreateDate = purcharsebill.CreateDate;
                }
                return d;
            }));
            datasource = (from t in datasource orderby t.Date, t.CreateDate select t).ToList();


            double toalOverage = 0;
            string lastGroup = string.Empty;
            datasource.Insert(0, new DataWrapper()
            {
                Date = startDate,
                Summary = "",
                ShouldPay = 0,
                RealPay = 0,
                Overage = toalOverage = DataAccess.PurchaseView.GetShouldPay(supplierId, startDate) - DataAccess.PaymentView.GetPaidAmount(supplierId, startDate)
            });
            foreach (var d in datasource)
            {
                d.Overage = toalOverage = toalOverage + d.ShouldPay - d.RealPay;
                if (string.Compare(lastGroup, d.Group) != 0)
                {
                    d.DateStr = d.Date.ToString("yyyy-MM-dd");
                    lastGroup = d.Group;
                }
            }

            this.rptData.DataSource = datasource;
            this.rptData.DataBind();
        }

        class DataWrapper
        {
            public string Group { get; set; }
            public DateTime Date { get; set; }
            public string Summary { get; set; }
            public double ShouldPay { get; set; }
            public double RealPay { get; set; }
            public double Overage { get; set; }
            public int Type { get; set; }
            public Guid BillID { get; set; }
            public DateTime CreateDate { get; set; }

            public string DateStr { get; set; }
            public string RealPayStr { get { return this.RealPay == 0 ? "" : this.RealPay.ToString("#,##0.00"); } }
            public string ShouldPayStr { get { return this.ShouldPay == 0 ? "" : this.ShouldPay.ToString("#,##0.00"); } }
        }
    }
}
